package online.dgyj.ele;

import android.animation.ObjectAnimator;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.LinearInterpolator;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Switch;
import android.widget.TextView;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.nle.mylibrary.claimer.connector.ConnectorListener;
import com.nle.mylibrary.databus.DataBusFactory;
import com.nle.mylibrary.device.GenericConnector;
import com.nle.mylibrary.device.listener.ConnectResultListener;

import java.util.concurrent.TimeUnit;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    Handler handler;

    private String EleIP;
    private int ElePort;
    private int EleAddress;
    private GenericConnector genericConnector;  // 通用连接器
    private boolean RTULink = false;
    private Thread EleThread = getSpeedThread();    // 电机速度线程
    private int EleSpeed;   // 电机速度
    long durationMillis = 0;  // 旋转速度 MAX 200 MIN 500

    TextView EleIPText, ElePortText, EleSpeedText;
    EditText EleIPEdit, ElePortEdit, EleAddressEdit;
    Switch EleLinkTypeSwitch;
    Button LinkBtn, SpeedUPBtn, SpeedDownBtn, ToggleBtn, StopBtn;
    ImageView imageView;
    ObjectAnimator animator;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);

        bind();

        // 创建一个ObjectAnimator对象，该对象将控制imageView的旋转
        // "rotation"参数表示我们要改变的属性是旋转角度
        // 0f和rotationDegree参数表示旋转的起始角度和结束角度
        animator = ObjectAnimator.ofFloat(imageView, "rotation", 0f, 360f);
        // 设置动画的重复次数为无限次
        animator.setRepeatCount(ObjectAnimator.INFINITE);
        // 设置插值器为LinearInterpolator，这意味着动画将以恒定的速度进行
        animator.setInterpolator(new LinearInterpolator());
        // 设置动画的持续时间(速度)，以毫秒为单位
        animator.setDuration(0);
        animator.start();

    }

    /**
     * 实例化控件
     */
    private void bind() {
        handler = new Handler(Looper.getMainLooper());

        EleIPText = findViewById(R.id.EleIPText);
        ElePortText = findViewById(R.id.ElePortText);
        EleSpeedText = findViewById(R.id.EleSpeedText);

        EleIPEdit = findViewById(R.id.EleIPEdit);
        ElePortEdit = findViewById(R.id.ElePortEdit);
        EleAddressEdit = findViewById(R.id.EleAddressEdit);

        EleLinkTypeSwitch = findViewById(R.id.EleLinkTypeSwitch);

        LinkBtn = findViewById(R.id.LinkBtn);
        SpeedUPBtn = findViewById(R.id.SpeedUPBtn);
        SpeedDownBtn = findViewById(R.id.SpeedDownBtn);
        ToggleBtn = findViewById(R.id.ToggleBtn);
        StopBtn = findViewById(R.id.StopBtn);

        imageView = findViewById(R.id.imageView);

        LinkBtn.setOnClickListener(this);
        SpeedUPBtn.setOnClickListener(this);
        SpeedDownBtn.setOnClickListener(this);
        ToggleBtn.setOnClickListener(this);
        StopBtn.setOnClickListener(this);

        EleLinkTypeSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                RTULink = isChecked;
                if (isChecked){
                    EleIPText.setText("Ele SerialName:");
                    ElePortText.setText("Ele Baud:");
                    EleIPEdit.setText("");
                    ElePortEdit.setText("");
                }else {
                    EleIPText.setText("Ele IP:");
                    ElePortText.setText("Ele Port:");
                    EleIPEdit.setText("");
                    ElePortEdit.setText("");
                }
            }
        });
    }

    /**
     * 获取电机速度
     *
     * @return 子线程
     */
    private Thread getSpeedThread() {
        return new Thread(new Runnable() {
            @Override
            public void run() {
                while (!Thread.currentThread().isInterrupted()) {
                    try {
                        genericConnector.sendEleGetSpeed(1, 1, new ConnectorListener() {
                            @Override
                            public void onSuccess(boolean b) {
                                Log.i("Speed", String.valueOf(genericConnector.getEleGetSpeed()));
                                EleSpeed = genericConnector.getEleGetSpeed();
                                EleSpeedView(genericConnector.getEleGetSpeed());
                            }

                            @Override
                            public void onFail(Exception e) {

                            }
                        });
                        TimeUnit.SECONDS.sleep(1);
                    } catch (Exception e) {
                        Log.e("Get Speed MSG", e.toString());
                        break;
                    }
                }
            }
        });
    }

    /**
     * 更新电机动画以及速度
     * @param speed 电机速度
     */
    void EleSpeedView(int speed) {
        handler.post(new Runnable() {
            @Override
            public void run() {
                if (speed >= 0 && speed <= 100) {
                    EleSpeedText.setText(String.format("%d%%", speed));
                    durationMillis = 500 - speed * 3L;
                    if (speed == 0) {
                        animator.setDuration(0);
                        animator.start();
                    } else {
                        if (animator.getDuration() == 0) {
                            animator.setDuration(durationMillis);
                            animator.start();
                        } else {
                            animator.setDuration(durationMillis);
                        }
                    }
                }
            }
        });
    }

    /**
     * 设置电机速度
     * @param speed 速度
     */
    void SetEleSpeed(int speed) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    genericConnector.sendEleSetSpeed(EleAddress, 1, speed, new ConnectorListener() {
                        @Override
                        public void onSuccess(boolean b) {
                            if (b) {
                                Log.i("SetSpeed", "OK");
                            }
                        }

                        @Override
                        public void onFail(Exception e) {

                        }
                    });
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        }).start();
    }

    /**
     * 设置电机刹车
     */
    void SetEleStop() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    genericConnector.sendEleStop(EleAddress, 1, new ConnectorListener() {
                        @Override
                        public void onSuccess(boolean b) {
                            if (b) {
                                Log.i("SetStop", "OK");
                            }
                        }

                        @Override
                        public void onFail(Exception e) {

                        }
                    });
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        }).start();
    }

    /**
     * 设置电机反向翻转
     */
    void SetEleToggle() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    genericConnector.sendEleGetDirection(EleAddress, 1, new ConnectorListener() {
                        @Override
                        public void onSuccess(boolean b) {
                            int cache;
                            if (genericConnector.getEleGetDirection() == 0) {
                                cache = 1;
                            } else {
                                cache = 0;
                            }
                            try {
                                genericConnector.sendEleSetDirection(EleAddress, 1, cache, new ConnectorListener() {
                                    @Override
                                    public void onSuccess(boolean b) {

                                    }

                                    @Override
                                    public void onFail(Exception e) {

                                    }
                                });
                            } catch (Exception e) {
                                throw new RuntimeException(e);
                            }
                        }

                        @Override
                        public void onFail(Exception e) {

                        }
                    });
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        }).start();
    }


    @Override
    public void onClick(View v) {
        // 连接按钮
        if (v.getId() == R.id.LinkBtn) {
            if (genericConnector == null) {
                // 读取输入的IP与Port
                EleIP = EleIPEdit.getText().toString();
                ElePort = Integer.parseInt(ElePortEdit.getText().toString());
                EleAddress = Integer.parseInt(EleAddressEdit.getText().toString());

                // 禁用控件
                EleIPEdit.setEnabled(false);
                ElePortEdit.setEnabled(false);
                EleAddressEdit.setEnabled(false);
                EleLinkTypeSwitch.setEnabled(false);

                // 判断连接方式
                if (RTULink) {
                    // 串口连接
                    genericConnector = new GenericConnector(DataBusFactory.newSerialDataBus(Integer.parseInt(EleIP), ElePort), new ConnectResultListener() {
                        @Override
                        public void onConnectResult(boolean b) {
                            if (b) {
                                Log.i("RTU  Status", "RTU Link OK!");

                                handler.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        LinkBtn.setText("DISC");
                                    }
                                });

                                EleThread.start();  // 开启转速获取线程

                            } else {
                                Log.i("RTU Status", "RTU Link Error!");

                                handler.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        // 启用控件
                                        EleIPEdit.setEnabled(true);
                                        ElePortEdit.setEnabled(true);
                                        EleAddressEdit.setEnabled(true);
                                        EleLinkTypeSwitch.setEnabled(true);

                                        LinkBtn.setText("Link");
                                    }
                                });
                            }
                        }
                    });
                }
                // TCP连接
                else {
                    genericConnector = new GenericConnector(DataBusFactory.newSocketDataBus(EleIP, ElePort), new ConnectResultListener() {
                        @Override
                        public void onConnectResult(boolean b) {
                            if (b) {
                                Log.i("TCP  Status", "TCP Link OK!");

                                handler.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        LinkBtn.setText("DISC");
                                    }
                                });

                                EleThread.start();

                            } else {
                                Log.i("TCP Status", "TCP Link Error!");

                                handler.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        // 启用控件
                                        EleIPEdit.setEnabled(true);
                                        ElePortEdit.setEnabled(true);
                                        EleAddressEdit.setEnabled(true);
                                        EleLinkTypeSwitch.setEnabled(true);

                                        LinkBtn.setText("Link");
                                    }
                                });
                            }
                        }
                    });
                }
            } else {
                // 启用控件
                EleIPEdit.setEnabled(true);
                ElePortEdit.setEnabled(true);
                EleAddressEdit.setEnabled(true);
                EleLinkTypeSwitch.setEnabled(true);

                LinkBtn.setText("Link");

                EleThread.interrupt();

                // 销毁
                genericConnector.stopConnect();
                genericConnector = null;
            }
        }
        // 提速按钮
        else if (v.getId() == R.id.SpeedUPBtn) {
            if (EleSpeed + 10 <= 100) {
                SetEleSpeed(EleSpeed + 10);
            } else {
                SetEleSpeed(100);
            }
        }
        // 降速按钮
        else if (v.getId() == R.id.SpeedDownBtn) {
            if (EleSpeed - 10 >= 0) {
                SetEleSpeed(EleSpeed - 10);
            } else {
                SetEleSpeed(0);
            }
        }
        // 反向按钮
        else if (v.getId() == R.id.ToggleBtn) {
            SetEleToggle();
        }
        // 刹车按钮
        else if (v.getId() == R.id.StopBtn) {
            SetEleStop();
        }
    }
}